/**
 * js效果文件
 */

//  获取当前域名
var ciHost = 'http://'+window.location.host+'/';
var ciHref = window.location.href+'/';

//  为空验证
function isempty(ipt_name,error_msg){
	var ipt_val = $("input[name="+ipt_name+"]").val();
	var error_msg = $.trim(error_msg)==''?'必填项不能为空':error_msg;
	if($.trim(ipt_val) == ''){
		alert(error_msg);
		return false;
	}
	return true;
}

//  取值
function getval(obj,type){
	var v = '';
	if(type == 'text'){
		v = $('#'+obj).text();
	}else if(type == 'html'){
		v = $('#'+obj).html();
	}else if(type == 'input'){
		v = $("input[name="+obj+"]").val();
	}else{
		v = $("#"+obj).val();
	}
	return v;
}


// 上传及时预览
function UploadShowImg(url,showimg,objfile,width,height){
	$("#"+objfile).trigger("click");
	$("#"+objfile).change(function(){
		if(url){
			$("#"+url).val(this.value);
		}
		if(this.files && this.files[0] && showimg) {  
			var reader = new FileReader();
			reader.onload = function (e) {
				$('#'+showimg).attr('src', e.target.result).width(width).height(height);  
			};
			reader.readAsDataURL(this.files[0]);  
		}
	});
}

// 全选OR反选
function checkAllorAnti(allAreaId,nowStatus,checkTextId) {
	nowStatus?$("#"+checkTextId).text("deselect all"):$("#"+checkTextId).text("check all");
    $("#"+allAreaId+" :input[type='checkbox']").each(function() {
        this.checked = nowStatus;
    });
}

// 判断当前是否已经选取了对象
function checkAllJudge(allAreaId,typeText) {
	var item = $("#"+allAreaId+" :checkbox:checked");
    var len = item.length;
    if(len>0){
    	return confirm('确定要'+typeText+'吗?');
    }else{
    	alert("请选择先!");
    }
    return false;
}

// 版本验证
function verifyversion(versionId) {
	var vs = $("#"+versionId).val();
	var myreg = /^(?:\d\.){2,3}\d$/;
	if (vs.replace(/^\s+|\s+$/g,'') == '' || !myreg.test(vs)) {
		alert('输入的版本号格式不正确');
		return false;
	}
	return true;
}


// 表格变色效果
function trbgmoves(overColor,outColor){
    if(!overColor)overColor='';
    if(!outColor)outColor='';
	$("tr.moves").mouseover(function() {
		$(this).css("background-color", overColor);
	});
	$("tr.moves").mouseout(function() {
		$(this).css("background-color", outColor);
	});

	$("tr.fixedmoves").mouseover(function() {
		$(this).css("color", "#FF6600");
	});
	$("tr.fixedmoves").mouseout(function() {
		$(this).css("color", outColor);
	});

}
(function($){
    $(function(){
        $.fn.filterSelect = (function(){
            return function(){
                var $body = $("body");
                this.each(function(i, v){
                    var $sel = $(v), $div = $('<div class="m-input-select"></div>');
                    var $input = $("<input type='text' class='m-input form-control' />");
                    var $wrapper = $("<ul class='m-list'></ul>");
                    //var $width = $sel.width()-22<=0?300:$sel.width()-22,$height = $sel.height()<=0?17:$sel.height();
                 
                    
                    if(!$sel.parent(".m-input-select").length){
                        $div = $sel.wrap($div).hide().addClass("m-select").parent();
                        $div.append($input).append("<span class='m-input-ico'></span>").append($wrapper);
                        //$input.css({"width":$width,"height":$height});
                        $div.parents("#contents").css({"overflow":"visible"});
                    }
                    var wrapper = {
                        show: function(){
                            $wrapper.show();
                            this.$list = $wrapper.find(".m-list-item:visible");
                            this.setIndex(this.$list.filter(".m-list-item-active"));
                            this.setActive(this.index);
                        },
                        hide: function(){
                            $wrapper.hide();
                        },
                        next: function(){
                            return this.setActive(this.index + 1);
                        },
                        prev: function(){
                            return this.setActive(this.index - 1);
                        },
                        $list: $wrapper.find(".m-list-item"),
                        index: 0,
                        $cur: [],
                        setActive: function(i){
                            var $list = this.$list, size = $list.size();
                            if(size <= 0){
                                this.$cur = [];
                                return;
                            }
                            $list.filter(".m-list-item-active").removeClass("m-list-item-active");
                            if(i < 0){
                                i = 0;
                            }else if(i >= size){
                                i = size - 1;
                            }
                            this.index = i;
                            this.$cur = $list.eq(i).addClass("m-list-item-active");
                            this.fixScroll(this.$cur);
                            return this.$cur;
                        },
                        fixScroll: function($elem){
                            var height = $wrapper.height(), top = $elem.position().top, eHeight = $elem.outerHeight();
                            var scroll = $wrapper.scrollTop();
                            top += scroll;
                            if(scroll > top){
                                $wrapper.scrollTop(top);
                            }else if(top + eHeight > scroll + height){
                                $wrapper.scrollTop(top + eHeight - height);
                            }
                        },
                        setIndex: function($li){
                            if($li.size() > 0){
                                this.index = this.$list.index($li);
                                $li.addClass("m-list-item-active").siblings().removeClass("m-list-item-active");
                            }else{
                                this.index = 0;
                            }
                        }
                    };
                    var operation = {
                        textChange: function(){
                            val = $.trim($input.val());
                            $wrapper.find(".m-list-item").each(function(i, v){
                                if(v.innerHTML.toLowerCase().indexOf(val.toLowerCase()) >= 0){
                                    $(v).show();
                                }else{
                                    $(v).hide();
                                }
                            });
                            wrapper.show();
                        },

                        setValue: function($li){
                            if($li && $li.size() > 0){
                                var val = $.trim($li.html());
                                $input.val(val).attr("placeholder", val);
                                wrapper.setIndex($li);
                                $sel.val($li.attr("data-value")).trigger("change");
                            }else{
                                $input.val(function(i, v){
                                    return $input.attr("placeholder");
                                });
                            };
                            wrapper.hide();
                            this.offBody();
                            $input.blur()
                        },
                        onBody: function(){
                            var self = this;
                            setTimeout(function(){
                                self.offBody();
                                $body.on("click", self.bodyClick);
                            }, 10);
                        },
                        offBody: function(){
                            $body.off("click", this.bodyClick);
                        },
                        bodyClick: function(e){
                            var target = e.target;
                            if(target != $input[0] && target != $wrapper[0]){
                                wrapper.hide();
                                operation.setValue();
                                operation.offBody();
                            }
                        }
                    };

                    function resetOption(){
                        var html = "", val = "";
                        $sel.find("option").each(function(i, v){
                            if(v.selected && !val){
                                val = v.text;
                            };
                            html += '<li class="m-list-item'+ (v.selected ? " m-list-item-active" : "") +'" data-value="'+ v.value +'">'+ v.text +'</li>';
                        });
                        $input.val(val);
                        $wrapper.html(html);
                    };
                    $sel.on("optionChange", resetOption).trigger("optionChange");
                    $sel.on("setEditSelectValue", function(e, val){
                        var $all = $wrapper.find(".m-list-item"), $item;
                        for(var i = 0, max = $all.size(); i < max; i++){
                            $item = $all.eq(i);
                            if($item.attr("data-value") == val){
                                operation.setValue($item);
                                return;
                            }
                        }
                    });

                    $input.on("focus", function(){
                        this.value = "";
                        operation.textChange();
                        operation.onBody();
                    }).on("input propertychange", function(e){
                        operation.textChange();
                    }).on("keydown", function(e){
                        switch(e.keyCode){
                            case 38:
                                wrapper.prev();
                                break;
                            case 40:
                                wrapper.next();
                                break;
                            case 13:
                                operation.setValue(wrapper.$cur);
                                break;
                        }
                    });

                    $div.on("click", ".m-input-ico", function(){
                        $wrapper.is(":visible") ? $input.blur() : ($input.val("").trigger("focus"));
                    });

                    $wrapper.on("click", ".m-list-item", function(){
                        operation.setValue($(this));
                        return false;
                    });

                    setTimeout(function(){
                        wrapper.hide();
                    }, 1)
                });
                return this;
            };
        })();

        /*layer tab弹出层重写*/
        $(".popupContainer .popupController span").on("click",function(){
             var indexNumber = $(this).index();
             $(this).addClass("layui-layer-tabnow").siblings().removeClass("layui-layer-tabnow");
             $(".popupContent .ct_content").removeClass("active").eq(indexNumber).addClass("active");
        });
        $(".layui-layer-setwin .popupClose").on("click",function(){
            $(".popupBg,.popupContainer").removeClass("active");
        });


        /*easy ui 表单验证扩展验证规则*/
        if(typeof $.fn.validatebox !== "undefined"){
            $.extend($.fn.validatebox.defaults.rules, {
                radio: {
                    validator: function (value, param) {
                        var frm = param[0], groupname = param[1], ok = false;
                        $('input[name="' + groupname + '"]', document[frm]).each(function () { 
                            if (this.checked) { ok = true; return false; }
                        });

                        return ok
                    },
                    message: '需要选择一项！'
                },
                intOrFloat: {// 验证整数或小数
                    validator: function (value) {
                        return /^\d+(\.\d+)?$/i.test(value);
                    },
                    message: '请输入数字，并确保格式正确'
                }
            });
        }

        

        /*同步第一行数据*/
        $(".synOperation").on("click",function(){
            var objItems = $(".basePriceM"),
                objFirst = objItems.eq(0),
                individualVaue = objFirst.find("[name^='individual_price']").val(),
                merchantVaue = objFirst.find("[name^='merchant_price']").val(),
                brandVaue = objFirst.find("[name^='brand_price']").val();
            
            if(!!individualVaue && parseFloat(individualVaue)){
                objItems.find("[name^='individual_price']").val(individualVaue);
            }
            if(!!merchantVaue && parseFloat(merchantVaue)){
                objItems.find("[name^='merchant_price']").val(merchantVaue);
            }
            if(!!brandVaue && parseFloat(brandVaue)){
                objItems.find("[name^='brand_price']").val(brandVaue);
            }
            
            return false;
        });

        /*只能输入数字和小数的验证*/
        $('.basePriceC .easyui-validatebox').on("keyup",function(e){
            var e = e||event,
                keyNumber = e.keyCode,
                $this = this;

            if($.inArray(keyNumber, [8, 35, 36, 37, 38, 39, 40, 46]) === -1){
                setTimeout(function(){
                    $this.value = $this.value.replace(/[^\d.\,]/g,"");
                    $this.value = $this.value.replace(/^[\.\,]/g,"");
                    $this.value = $this.value.replace(/^(\-)*(\d+)([\.\,])(\d{0,2})[\,\.]*.*$/,'$1$2$3$4'); 
                 },0);
                
            }
        });

        /*新菜单效果*/
        var obj = $("#menu .menu-oms");
        obj.addClass("active open").parents(".collapse").addClass("in").end().parents(".catalog-second").addClass("active open");
        
        /*$('#menu a[href]').on('click', function() {
            sessionStorage.setItem('menu', $(this).attr('href'));
        });

        if (!sessionStorage.getItem('menu')) {
            $('#menu #dashboard').addClass('active');
        } else {
            $('#menu a[href=\'' + sessionStorage.getItem('menu') + '\']').parents('li').addClass('active open');
        }

        if (localStorage.getItem('column-left') == 'active') {
            $('#button-menu i').replaceWith('<i class="fa fa-dedent fa-lg"></i>');
            $('#column-left').addClass('active');
            $('#menu li.active').has('ul').children('ul').addClass('collapse in');
            $('#menu li').not('.active').has('ul').children('ul').addClass('collapse');
        } else {
            $('#button-menu i').replaceWith('<i class="fa fa-indent fa-lg"></i>');
            $('#menu li li.active').has('ul').children('ul').addClass('collapse in');
            $('#menu li li').not('.active').has('ul').children('ul').addClass('collapse');
        }*/

        $('#button-menu').on('click', function() {
            if ($('#column-left').hasClass('active')) {
                localStorage.setItem('column-left', '');
                $('#button-menu i').replaceWith('<i class="fa fa-indent fa-lg"></i>');
                $('#column-left').removeClass('active');
                $('#menu > li > ul').removeClass('in collapse');
                $('#menu > li > ul').removeAttr('style');
            } else {
                localStorage.setItem('column-left', 'active');
                $('#button-menu i').replaceWith('<i class="fa fa-dedent fa-lg"></i>');
                $('#column-left').addClass('active');
                $('#menu li.open').has('ul').children('ul').addClass('collapse in');
                $('#menu li').not('.open').has('ul').children('ul').addClass('collapse');
            }
        });

        $('#menu').find('li').has('ul').children('a').on('click', function() {
            if ($('#column-left').hasClass('active')) {
                $(this).parent('li').toggleClass('open').children('ul').collapse('toggle');
                $(this).parent('li').siblings().removeClass('open').children('ul.in').collapse('hide');
            } else if (!$(this).parent().parent().is('#menu')) {
                $(this).parent('li').toggleClass('open').children('ul').collapse('toggle');
                $(this).parent('li').siblings().removeClass('open').children('ul.in').collapse('hide');
            }
        });

    });
})(jQuery);

//JSON转化为表格
function appendTable(data,elementId)
{
    var oneRow =data[0];
    var headArray=Array();
    for(var i in oneRow)
    {
        headArray[headArray.length] = i;
    }
    var table= document.createElement("table");     
    var thead = document.createElement("tr");
    for(var count =0;count<headArray.length;count++)
    {
        var td = document.createElement("td");
        td.innerHTML= headArray[count];
        thead.appendChild(td);
    }
    table.appendChild(thead);
    for(var tableRowNo =0; tableRowNo<data.length;tableRowNo++)
    {       
        var tr = document.createElement("tr");
        for(var headCount = 0; headCount<headArray.length; headCount++)
        {
            var cell = document.createElement("td");
            cell.innerHTML = data[tableRowNo][headArray[headCount]];
            tr.appendChild(cell);
        }
        table.appendChild(tr);
    }
    while(document.getElementById(elementId).hasChildNodes())
    {
        document.getElementById(elementId).removeChild(div.firstChild);
    }
    document.getElementById(elementId).appendChild(table);
}
//获取cookie
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
//删除cookie
function delCookie(name)
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
//设置cookie
function setCookie(name,value,time)
{
var strsec = time;
var exp = new Date();
exp.setTime(exp.getTime() + strsec*1);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}